import "../lib/jquery.js";
import axios from "../lib/axios.js";

$(function () {
  // 有登陆直接前往首页
  if (localStorage.getItem("authorization")) {
    location.href = "index.html";
  }

  $("#form").submit(function (e) {
    e.preventDefault();

    var formData = {};
    $("form input").each(function () {
      formData[$(this).attr("class")] = $(this).val();
    });

    axios
      .post("http://localhost:9000/users/login", formData)
      .then(({ data }) => {
        if (data.code !== 1) {
          $("span.error").show().text(data.message);
        } else {
          $("span.error").hide();
          localStorage.setItem("authorization", data.token);
          localStorage.setItem("user", JSON.stringify(data.user));
          alert("登陆成功");
          location.href = "index.html";
        }
      });
  });
});
